module.exports = function ($scope, $resource, $modal, $modalInstance, toaster, sale_info, $timeout, Excel) {
    $scope.userList = [];
    $scope.sale_info = sale_info;
    $scope.order_info = {
        'name': '',
        'cardno': '',
        'mobile': '',
        'by_bus': '1',
        'note': '',
        'contact_account': $scope.sale_info.id,
        'tour_date': $scope.sale_info.tour_date,
        'order_source': '0'
    };
    
    //添加购票人
    $scope.add = function () {
        $scope.userList.push({
            'name': '',
            'cardno': '',
            'mobile': '',
            'by_bus': '1',
            'note': '',
            'desc': '未校验',
            'state': 2,
            'contact_account': $scope.sale_info.id,
            'tour_date': $scope.sale_info.tour_date,
            'order_source': '0'
        })
    }
    
    //删除购票人
    $scope.remove = function (index) {
        $scope.userList.splice(index, 1);
    }
    
    //删除所有购票人
    $scope.removeAll = function (index) {
        $scope.userList = [];
    }
    
    //导入excel
    $scope.excel = function () {
        var modalInstance = $modal.open({
            template: require('../views/tourAddUserBatch.html'),
            controller: 'tourAddUserBatch',
            size: 'lg',
            resolve: {
            }
        });
        //关闭模态框刷新页面
        modalInstance.result.then(function (result) {
            if (result.list && result.list.length > 0) {
                angular.forEach(result.list, function(item){
                    const element = {
                        'name': item[result.name].replace(/\s+/g,""),
                        'cardno': item[result.cardno].replace(/\s+/g,""),
                        'mobile': item[result.mobile].replace(/\s+/g,""),
                        'by_bus': item[result.by_bus].indexOf('跟车') != -1 ? '1' : '0',
                        'by_bus_msg': item[result.by_bus].indexOf('跟车') != -1 ? true : false,
                        'state': '2',
                        'desc': '未校验'
                    };
                    $scope.is_pass(element)
                    $scope.userList.push(element);
                });
            }
        });
    }

    //导出Excel
    $scope.ExcelName = date2str(new Date());
    $scope.exportToExcel = function (tableId) {
        $timeout(function () {
            document.getElementById("dlink").href = Excel.tableToExcel(tableId, 'sheet1');
            //document.getElementById("dlink").download = "1122b.xls";//这里是关键所在,当点击之后,设置a标签的属性,这样就可以更改标签的标题了
            document.getElementById("dlink").click();
        }, 100); // trigger download
    }

    //确定购票
    $scope.ok = function () {
        $scope.createOrder(0);
    }
    //实际下单
    $scope.createOrder = function (index) {
        if(index >= $scope.userList.length){
            return false;
        }
        const order_info = $scope.userList[index];
        order_info.is_creating = true;
        if (order_info.state == 4 || (order_info.state != 1 && !$scope.is_pass(order_info))) {
            order_info.is_creating = false;
            $scope.createOrder(++index);
            return false;
        }
        order_info.state = 3;
        order_info.desc = '下单中';
        let para = {
            cardno: order_info.cardno,
            name: order_info.name,
            mobile: order_info.mobile,
            by_bus: order_info.by_bus_msg? '1': '0',
            note: order_info.note,
            contact_account: $scope.sale_info.id,
            tour_date: $scope.sale_info.tour_date,
            order_source: '0'
        }
        $resource('/api/ac/ggc/voluntourismOrderService/createOrder', {}, {}).save(para, function (res) {
            if (res.errcode === 0) {
                order_info.is_creating = false;
                order_info.desc = `【下单成功】${para.cardno}`;
                order_info.state = 4;
                toaster.success({ title: order_info.name, body: res.errmsg });
            } else {
                order_info.state = 2;
                order_info.desc = res.errmsg;
                order_info.is_creating = false;
                toaster.error({ title: order_info.name, body: res.errmsg });
            }
            $scope.createOrder(++index);
        });
    }

    //取消
    $scope.close = function () {
        $modalInstance.dismiss('cancel');
    }

    //校验
    $scope.is_pass = function (obj) {
        if (obj.state == 4) {
            return false;
        }
        obj.state = 3;
        let nocard = false;
        if (!checkCardNo(obj.cardno)) {
            obj.state = 2;
            obj.desc = '身份证信息有误';
            return false;
        }
        if (obj.name == "") {
            obj.state = 2;
            obj.desc = '请填写姓名';
            return false;
        }
        if (!isMobil(obj.mobile)) {
            obj.state = 2;
            obj.desc = '请输入正确电话号码';
            return false;
        }
        obj.state = 1;
        obj.desc = '校验成功';
        return true;
    }

    //校验身份证
    var checkCardNo = function (code) {
        var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 " };
        var tip = "";
        var pass = true;
        if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
            tip = "身份证号格式错误";
            pass = false;
        } else if (!city[code.substr(0, 2)]) {
            tip = "身份证地址编码错误";
            pass = false;
        } else {
            //18位身份证需要验证最后一位校验位
            if (code.length == 18) {
                code = code.split('');
                //∑(ai×Wi)(mod 11)
                //加权因子
                var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                //校验位
                var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
                var sum = 0;
                var ai = 0;
                var wi = 0;
                for (var i = 0; i < 17; i++) {
                    ai = code[i];
                    wi = factor[i];
                    sum += ai * wi;
                }
                var last = parity[sum % 11];
                if (parity[sum % 11] != code[17]) {
                    tip = "身份证校验位错误";
                    pass = false;
                }
            }
        }
        return pass;
    }

    /**
     * 验证手机号
     * @param {需要校验的手机号} mobile
     * @return 错误返回 false , 正确返回 true
     */
    function isMobil(mobile) {
        var patrn = /(^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$)/;
        if (!patrn.exec(mobile)) {
            return false;
        }
        return true;
    }

    //日期格式转换
    function date2str(d) {
        if (d === undefined) {
            return "";
        }
        var month = (d.getMonth() + 1).toString();
        var day = d.getDate().toString();
        if (month.length == 1) month = '0' + month;
        if (day.length == 1) day = '0' + day;
        return d.getFullYear() + "-" + month + "-" + day;
    }

};